const Router=require('koa-router');
const fs=require('await-fs');
const path=require('path');
const common=require('../../libs/common')

let router = new Router();

const table='banner_table';

router.get('/login',async ctx=>{
    await ctx.render('admin/login',{
        HTTP_ROOT:ctx.config.HTTP_ROOT,
        errmsg:ctx.query.errmsg
    })
})
router.post('/login',async ctx=>{
    const {HTTP_ROOT}=ctx.config;
    let {username,password}=ctx.request.fields;

    let admins=JSON.parse((await fs.readFile(
        path.resolve(__dirname,'../../admins.json')
    )).toString());
    function findAdmin(username){
        let a=null;
        admins.forEach(admin => {
            if(admin.username == username){
                a=admin
            }
        });
        return a;
    }
    let admin=findAdmin(username)
    if(!admin){
        ctx.redirect(`${HTTP_ROOT}/admin/login?errmsg=${encodeURIComponent('用户不存在')}`);
    }else if(admin.password != common.md5(password)){
        console.log(admin.password)
        console.log(common.md5(password));
        ctx.redirect(`${HTTP_ROOT}/admin/login?errmsg=${encodeURIComponent('密码不对')}`);
    }else{
        ctx.session['admin']=username;
        ctx.redirect(`${HTTP_ROOT}/admin/`);
    }
})

router.all('*', async (ctx, next)=>{
    let {HTTP_ROOT}=ctx.config;
  
    if(ctx.session['admin']){
      await next();
    }else{
      //ctx.body='你不是管理员';
      ctx.redirect(`${HTTP_ROOT}/admin/login`);
    }
  });
  
  router.get('/', async ctx=>{
    const {HTTP_ROOT}=ctx.config;
  
    ctx.redirect(`${HTTP_ROOT}/admin/banner`);
  });
  
  
  
  const fields=[
    {title: '标题', name: 'title', type: 'text'},
    {title: '图片', name: 'src', type: 'file'},
    {title: '链接', name: 'href', type: 'text'},
    {title: '序号', name: 'serial', type: 'number'},
  ];
  router.get('/banner', async ctx=>{
    const {HTTP_ROOT}=ctx.config;
  
    let datas=await ctx.db.query(`SELECT * FROM ${table}`);
    ctx.body=datas;
  
    // await ctx.render('admin/table', {
    //   HTTP_ROOT,
    //   type: 'view',
    //   datas,
    //   action: `${HTTP_ROOT}/admin/banner`,
    //   fields
    // })
  });
  
  router.post('/banner', async ctx=>{
   
  });
  
  
  
  router.get('/banner/delete/:id/', async ctx=>{
    
  });
  
  router.get('/banner/modify/:id/', async ctx=>{

  })
    
  
  router.post('/banner/modify/:id/', async ctx=>{
    ctx.body='a';
  });
  
  
  
  
  
  
  
  
  
  
  
  
  
  router.get('/catalog', async ctx=>{
    ctx.body='bbb';
  });
  
  router.get('/article', async ctx=>{
    ctx.body='ccc';
  });
module.exports=router.routes()